using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace winsw
{
	internal class Service : IDisposable
	{
		internal IntPtr Handle;

		internal Service(IntPtr service)
		{
			Handle = service;
		}

		public void ChangeConfig(TimeSpan failureResetPeriod, List<SC_ACTION> actions)
		{
			SERVICE_FAILURE_ACTIONS sfa = default(SERVICE_FAILURE_ACTIONS);
			sfa.dwResetPeriod = failureResetPeriod.Seconds;
			sfa.lpRebootMsg = "";
			sfa.lpCommand = "";
			int num = Marshal.SizeOf(typeof(SC_ACTION));
			sfa.cActions = actions.Count;
			sfa.lpsaActions = Marshal.AllocHGlobal(num * actions.Count);
			try
			{
				for (int i = 0; i < actions.Count; i++)
				{
					Marshal.StructureToPtr(actions[i], new IntPtr(sfa.lpsaActions.ToInt64() + i * num), fDeleteOld: false);
				}
				if (!Advapi32.ChangeServiceConfig2(Handle, SERVICE_CONFIG_INFOLEVEL.SERVICE_CONFIG_FAILURE_ACTIONS, ref sfa))
				{
					throw new Exception("Failed to change the failure actions", new Win32Exception());
				}
			}
			finally
			{
				Marshal.FreeHGlobal(sfa.lpsaActions);
			}
		}

		public void Dispose()
		{
			if (Handle != IntPtr.Zero)
			{
				Advapi32.CloseServiceHandle(Handle);
			}
			Handle = IntPtr.Zero;
		}
	}
}
